package com.ruyuan.seckilling.purchase.async.listener;

import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.OrderCreateMessage;
import com.ruyuan.seckilling.purchase.async.BasePurchaseListener;
import com.ruyuan.seckilling.purchase.async.PurchaseContext;
import com.ruyuan.seckilling.purchase.async.event.Step4CreateOrder;
import com.ruyuan.seckilling.purchase.async.event.Step5Response;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发送创建秒杀订单的消息
 *
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel("step4")
public class Step4Listener extends BasePurchaseListener<Step4CreateOrder> {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Step4CreateOrder;
    }

    @Override
    protected void doThisStep(Step4CreateOrder event, PurchaseContext purchaseContext) {
       executorService.execute("step4", () -> {
           String message = OrderCreateMessage.builder()
                   .sequence(purchaseContext.getSequence())
                   .activityId(purchaseContext.getActivityId())
                   .userId(purchaseContext.getUserId())
                   .skuId(purchaseContext.getSkuId())
                   .count(1).build().toJsonString();
           rocketMQTemplate.convertAndSend(QueueKey.QUEUE_CREATE_ORDER, message);

           log.info("发送创建秒杀订单的消息");

           bossEventBus.publish("step5", new Step5Response(), purchaseContext);
       });
    }
}
